package com.pr.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("news")
public class NewsController {

    private static final Logger log = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;  // loadBalancer LB负载均衡：自带算法  默认轮训

    @Autowired
    private DiscoveryClient discoveryClient;

    //远程调用公告服务接口
    @GetMapping("/page")
    public String page() throws Exception {
        // serviceInstance 服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("news-service");
        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/news/list");
        log.info("访问的服务器是:"+url);
        String response = restTemplate.getForObject(url, String.class);
        return response;
    }

    @GetMapping("/page1")
    public String page1() throws Exception {
        //服务列表
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("news-service");
        int index = new Random().nextInt(serviceInstanceList.size()); // 0-1
        //任意选择一个，实现本地RPC调用
        ServiceInstance serviceInstance = serviceInstanceList.get(index); // 0 1
        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/news/list");
        String response = restTemplate.getForObject(url, String.class);
        log.info("访问的服务器是:"+url);
        return response;
    }

}
